<?php
/**
 * Created by PhpStorm.
 * User: 64423
 * Date: 2018/10/31
 * Time: 10:58
 */

namespace app\shop\home;

use app\shop\model\CartModel;
use app\shop\model\GoodsModel;
use app\shop\model\SpecPriceModel;

class Cart
{
    // 加入购物车操作
    public function addInCart()
    {
        $user_id = 1;
        $goods_id = input('get.goods_id');
        $goods_num = input('post.goods_num', 1);
        $spec_key = input('get.spec_key', 0);
        $goods_info = GoodsModel::getOne($goods_id);

        $data = [
            'user_id' => $user_id,
            'goods_id' => $goods_info['id'],
            'goods_name' => $goods_info['name'],
            'goods_img' => $goods_info['original_img'],
            'goods_num' => $goods_num,
            'price' => $goods_info['shop_price']
        ];
        if($spec_key != 0){
            $spec = SpecPriceModel::getByKey($goods_id,$spec_key);

            $data['spec_name'] = $spec['key_name'];
            $data['spec_key'] = $spec['key'];
            $data['price'] = $spec['price'];
        }
        $data['add_time'] = time();
        if(!$this->goodsNumIsAdd($user_id, $goods_id,$spec_key, $goods_num)) {
            CartModel::addInCart($data);
        }
        return _json('2000', '','成功加入购物车');
    }

    // 获取购物车商品数量
    public function getCartNum()
    {
        $user_id = 1;
        $num = CartModel::getCartNum($user_id);
        return _json('2000', $num);
    }

    // 获取购物车列表
    public function getCartList()
    {
        $user_id = 1;
        $list = CartModel::getCartList($user_id);
        $list = getImagePath($list, 'goods_img');
        return _json('2000', $list);
    }

    // 改变购物车商品选中状态
    public function changeItemSelected()
    {
        $id = input('param.id');
        $selected = input('param.selected');
        CartModel::changeItemSelected($id, $selected);
        return _json('2000','', '成功');
    }

    // 改变购物车商品数量
    public function changeItemNum()
    {
        $id = input('param.id');
        $num = input('param.num');
        CartModel::changeItemNum($id, $num);
        return _json('2000', '', '成功');
    }

    /**
     * 判断购物车是否存在当前商品
     * 存在则数量加
     * @param $user_id
     * @param $goods_id
     * @param $spec_key
     * @param $add_num
     * @return bool|int|true
     */
    private function goodsNumIsAdd($user_id, $goods_id, $spec_key, $add_num)
    {
        if(CartModel::goodsExist($user_id, $goods_id, $spec_key)){
            return CartModel::addGoodsNum($user_id, $goods_id, $spec_key, $add_num);
        }else{
            return false;
        }
    }

}